﻿using Inovout.Kuajing.Models;
using Inovout.Runtime;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using WallF.BaseNEncodings;

namespace Inovout.Kuajing.Services
{
    class WangCangStoreService
    {
        static readonly string secret = "kuajing123456";
        static readonly string platform_id = "216";
        static readonly string url = "http://testapi.iscs.com.cn/bsbusiness";


        static WangCangStoreService()
        {
            var settings = ComponentRegistry.Resolve<IApplication>().Settings;
            secret = settings["secret"].ToString();
            platform_id = settings["platform_id"].ToString();
            url = settings["url"].ToString();

        }
        /// <summary>
        /// 3.3
        /// </summary>
        /// <param name="shipmentOrder"></param>
        /// <returns></returns>
        internal bool Ship(ShipmentOrder order)
        {
            Commodity commodity = order.Items.First().Commodity;
            JObject data = new JObject();
            data["orderCode"] = order.No;
            JArray result = (JArray)Execute("NOTIFY_WMS_PACKAGE", commodity.StoreCode, commodity.ExternalShipperId, data);
            return result == null;
        }

        /// <summary>
        /// 3.14 获取有效库存
        /// </summary>
        /// <param name="commodity"></param>
        /// <returns></returns>
        internal int GetCommoditAvailableSaleQuantity(Commodity commodity)
        {
            JObject data = new JObject();
            data["sellerUserId"] = commodity.ExternalShipperId;
            JObject itemData = new JObject();
            itemData["itemId"] = commodity.Id.ToString();
            itemData["productNo"] = commodity.Code;
            itemData["sellerUserId"] = commodity.ExternalShipperId;
            //itemData["qtyOfShipping"] = 11;
            //itemData["inventoryType"] = 1;

            data["itemIds"] = JArray.FromObject(new JObject[] { itemData });
            JArray result = (JArray)Execute("INVENTORY_QUERY", commodity.StoreCode, commodity.ExternalShipperId, data);
            var jStore = result.Count() == 0 ? 0 : result.Single(q => q["inventoryType"].ToString().Equals("1"))["qtyOfAvailable"];
            return (int)jStore;

        }

        internal bool CreatePurchaseOrder(PurchaseOrder order)
        {

            Commodity commodity = order.Items.First().Commodity;
            JObject data = new JObject();
            data["storeCode"] = commodity.StoreCode;
            data["sellerUserId"] = commodity.ExternalShipperId;
            data["orderCode"] = order.No;
            data["orderType"] = 601;
            data["orderCreateTime"] = order.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss");

            List<JObject> itemDatas = new List<JObject>();
            foreach (var item in order.Items)
            {
                JObject itemData = new JObject();
                itemData["orderItemId"] = item.Id.ToString();
                itemData["sellerUserId"] = item.Commodity.ExternalShipperId;
                itemData["inventoryType"] = 1;
                itemData["itemId"] = item.Commodity.Id.ToString();
                itemData["itemName"] = item.CommodityName;
                itemData["productNo"] = item.Commodity.Code;
                itemData["itemQty"] = item.CommodityQuantity;
                itemDatas.Add(itemData);
            }
            data["orderItemList"] = JArray.FromObject(itemDatas.ToArray());

            return null == Execute("PURCHASE_ORDER_NOTIFY", commodity.StoreCode, commodity.ExternalShipperId, data);


        }

        internal bool CreateShipmentOrderr(ShipmentOrder order)
        {

            Commodity commodity = order.Items.First().Commodity;
            JObject data = new JObject();
            data["storeCode"] = commodity.StoreCode;
            data["sellerUserId"] = commodity.ExternalShipperId;
            data["orderCode"] = order.No;

            data["orderCreateTime"] = order.CreatedTime.ToString("yyyy-MM-dd HH:mm:ss");
            data["orderPayTime"] = order.CreatedTime.ToString("yyyy-MM-dd HH:mmss");
            data["totalFee"] = order.Amount;
            data["payment"] = order.Amount;
            data["discountFee"] = 0;
            data["postFee"] = 0;

            data["receiverZipCode"] = order.ReceiverZipcode;
            data["receiverProvince"] = order.ReceiverProvince;
            data["receiverCity"] = order.ReceiverCity;
            data["receiverCounty"] = order.ReceiverCounty;
            data["receiverAddress"] = order.ReceiverAddress;
            data["receiverName"] = order.ReceiverName;
            data["receiverMobile"] = order.ReceiverMobile;
            data["receiverPhpne"] = order.ReceiverPhone;
            List<JObject> itemDatas = new List<JObject>();
            foreach (var item in order.Items)
            {
                JObject itemData = new JObject();
                itemData["orderItemId"] = item.Id.ToString();
                itemData["sellerUserId"] = item.Commodity.ExternalShipperId;
                itemData["itemId"] = item.Commodity.Id.ToString();
                itemData["itemName"] = item.CommodityName;
                itemData["productNo"] = item.Commodity.Code;
                itemData["itemQty"] = item.CommodityQuantity;
                itemDatas.Add(itemData);
            }
            data["orderItemList"] = JArray.FromObject(itemDatas.ToArray());

            return null == Execute("WMS_ORDER_NOTIFY", commodity.StoreCode, commodity.ExternalShipperId, data);


        }
        private JToken Execute(string notify_type, string store_code, string seller_user_id, JObject data)
        {
            Dictionary<string, string> body = new Dictionary<string, string>();
            body["notify_type"] = notify_type;
            body["notify_id"] = DateTime.Now.Ticks.ToString();
            body["format"] = "json";
            body["notify_time"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            body["platform_id"] = platform_id;
            body["store_code"] = store_code;
            body["seller_user_id"] = seller_user_id;

            string json = data.ToString();
            String md5Value = getMD5(json + secret, null);

            String reSign = BaseEncoding.Base64.ToBaseString(UTF8Encoding.UTF8.GetBytes(md5Value));
            body["data"] = json;
            body["sign"] = reSign;
            HttpClient http = new HttpClient();
            HttpContent content = new FormUrlEncodedContent(body);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded;charset=UTF-8");


            var response = http.PostAsync(url, content);
            response.Wait();
            var responseText = response.Result.Content.ReadAsStringAsync();
            responseText.Wait();

            JObject result = JObject.Parse(responseText.Result);

            if ((bool)result["success"])
            {
                return ((IEnumerable<KeyValuePair<string, JToken>>)result).SingleOrDefault(kv => !kv.Key.Equals("success") && !kv.Key.Equals("errorMsg") && !kv.Key.Equals("errorCode")).Value;
            }
            throw new Exception(responseText.Result);
        }


        public static String getMD5(String orgin, String charset)
        {
            if (charset == null) charset = "utf-8";
            String result = null;
            try
            {
                MD5 md = MD5.Create();

                result = byte2hex(md.ComputeHash(Encoding.GetEncoding(charset).GetBytes(orgin)));
            }
            catch (Exception e)
            {
                throw e;
            }
            return result;
        }
        private static String byte2hex(byte[] b)
        {
            StringBuilder hs = new StringBuilder();
       
            for (int n = 0; n < b.Length; n++)
            {
                string hex = (b[n] & 0XFF).ToString("x");
                if (hex.Length == 1)
                {
                    hs.Append("0");
                }
                hs.Append(hex);
            }
            return hs.ToString();
        }



    }
}
